package com.example.huangyuchen.advance.training.camp.week02.netty.inbound;

import com.example.huangyuchen.advance.training.camp.week02.netty.NettyServerApplication;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import lombok.experimental.FieldDefaults;

import java.util.Collections;
import java.util.List;

/**
 * @author YuChen Huang
 * @date 2022/1/22 22:15
 */
@FieldDefaults(level = AccessLevel.PRIVATE)
@AllArgsConstructor
@Getter
@ToString
public class CustomHttpInboundServer {

    public static void main(String[] args) {
        final CustomHttpInboundServer inboundServer = new CustomHttpInboundServer(8888, Collections.singletonList(NettyServerApplication.GATEWAY_URL));

        try {
            inboundServer.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 端口号
     */
    int port;

    List<String> proxyServer;

    public void run() throws Exception{

        final NioEventLoopGroup bossGroup = new NioEventLoopGroup(2);
        final NioEventLoopGroup workerGroup = new NioEventLoopGroup(16);

        try {
            final ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.SO_REUSEADDR, true)
                    .childOption(ChannelOption.SO_RCVBUF, 32 * 1024)
                    .childOption(ChannelOption.SO_SNDBUF, 32 * 1024)
                    .childOption(EpollChannelOption.SO_REUSEPORT, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new CustomHttpInboundInitializer(this.proxyServer));

            final Channel channel = serverBootstrap.bind(port).sync().channel();
            System.out.println("开启Netty Http Server，监听地址和端口为" + proxyServer.get(0) + ':' + port + '/');
            channel.closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

